import 'package:json_annotation/json_annotation.dart';

part 'budget_model.g.dart';

/// 预算模型
/// 用于管理用户的各个分类预算
@JsonSerializable()
class BudgetModel {
  /// 预算ID
  final String id;

  /// 预算分类
  final String category;

  /// 预算金额（单位：元）
  @JsonKey(name: 'budget_amount')
  final double budgetAmount;

  /// 已支出金额（单位：元）
  @JsonKey(name: 'spent_amount')
  final double spentAmount;

  /// 预算月份
  final int month;

  /// 预算年份
  final int year;

  /// 预算创建时间
  @JsonKey(name: 'created_at')
  final DateTime createdAt;

  /// 构造函数
  BudgetModel({
    required this.id,
    required this.category,
    required this.budgetAmount,
    required this.spentAmount,
    required this.month,
    required this.year,
    required this.createdAt,
  });

  /// 从JSON创建对象
  factory BudgetModel.fromJson(Map<String, dynamic> json) =>
      _$BudgetModelFromJson(json);

  /// 转换为JSON
  Map<String, dynamic> toJson() => _$BudgetModelToJson(this);

  /// 获取预算使用百分比（0-100）
  double get percentage =>
      (spentAmount / budgetAmount * 100).clamp(0, 100);

  /// 获取剩余预算
  double get remaining => (budgetAmount - spentAmount).clamp(0, double.infinity);

  /// 是否超出预算
  bool get isOverBudget => spentAmount > budgetAmount;

  /// 复制并更新属性
  BudgetModel copyWith({
    String? id,
    String? category,
    double? budgetAmount,
    double? spentAmount,
    int? month,
    int? year,
    DateTime? createdAt,
  }) {
    return BudgetModel(
      id: id ?? this.id,
      category: category ?? this.category,
      budgetAmount: budgetAmount ?? this.budgetAmount,
      spentAmount: spentAmount ?? this.spentAmount,
      month: month ?? this.month,
      year: year ?? this.year,
      createdAt: createdAt ?? this.createdAt,
    );
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is BudgetModel &&
          runtimeType == other.runtimeType &&
          id == other.id;

  @override
  int get hashCode => id.hashCode;
}
